import sys
from xml.sax import make_parser 
from xml.sax.handler import ContentHandler
from jd_handler import JD_Tag,JD_Handler

class Item(object):
    def __init__(self):
        self.key=''
        self.value=''
        self.remark=''

class XConfig(JD_Handler):
    def __init__(self):
        #essential info
        basicSchema = {'xconfig':JD_Tag(1),'item':JD_Tag(2),'value':JD_Tag(3),'remark':JD_Tag(3)}
        JD_Handler.__init__(self, basic=basicSchema)
        #data
        self.version = ''
        self.item = None
        self.items = []
        
    def characters(self, content):
        if self.expect_tag('value') or self.expect_tag('remark') :
            self.chars.append(content)
        
    def startElement(self, name, atts):
        self.in_tag(name)
        if self.expect_tag('item'):
            self.item = Item()
            self.item.key = atts['key']
    
    def endElement(self, name):
        if self.expect_tag('value') and self.item :
            self.item.value = ''.join(self.chars)
            self.chars = []
        elif self.expect_tag('remark') and self.item :
            self.item.remark = ''.join(self.chars)
            self.chars = []
        elif self.expect_tag('item') and self.item :
            self.items.append(self.item)
        self.out_tag(name)

    def load(self, configPath):
        parser = make_parser()
        parser.setContentHandler(self)
        parser.parse(configPath)

if __name__ == '__main__':
    if len(sys.argv)<2 :
        print 'usage: %s config-file' % sys.argv[0]
        exit
    xconf = XConfig()
    xconf.load(sys.argv[1])
    for item in xconf.items:
        print 'item[%s]="%s"' % (item.key,item.value)
